<template>
  <n-card
      :style="{'width':clientWidth>1025?'40%':'96%'}"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
   >
    <n-spin :show="showloading">

    <n-tabs
      v-model:value="activeTab"
      default-value="signin"
      size="large"
      justify-content="space-evenly"
    >



      <n-tab-pane name="signin" tab="登录">
        <n-form>
          <n-form-item-row label="用户名">
            <n-input
              ref="loginUserNameRef"
              @keydown.enter="loginBtn"
              clearable
              placeholder="请输入用户名"
              v-model:value="loginForm.uName"
            />
          </n-form-item-row>
          <n-form-item-row label="密码">
            <n-input
              ref="loginUserPwdRef"
              @keydown.enter="loginBtn"
              clearable
              show-password-on="mousedown"
              placeholder="请输入密码"
              type="password"
              v-model:value="loginForm.uPwdword"
            />
          </n-form-item-row>
        </n-form>
     <n-space justify="center">
       <!-- <n-button type="error" block secondary strong>
         <template #icon>
           <n-icon>
             <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 448 512"><path d="M433.754 420.445c-11.526 1.393-44.86-52.741-44.86-52.741c0 31.345-16.136 72.247-51.051 101.786c16.842 5.192 54.843 19.167 45.803 34.421c-7.316 12.343-125.51 7.881-159.632 4.037c-34.122 3.844-152.316 8.306-159.632-4.037c-9.045-15.25 28.918-29.214 45.783-34.415c-34.92-29.539-51.059-70.445-51.059-101.792c0 0-33.334 54.134-44.859 52.741c-5.37-.65-12.424-29.644 9.347-99.704c10.261-33.024 21.995-60.478 40.144-105.779C60.683 98.063 108.982.006 224 0c113.737.006 163.156 96.133 160.264 214.963c18.118 45.223 29.912 72.85 40.144 105.778c21.768 70.06 14.716 99.053 9.346 99.704z" fill="currentColor"></path></svg>
           </n-icon>
         </template>
         QQ登录
       </n-button> -->
       <n-button type="info" block secondary strong @click="loginBtn">
         确认登录
       </n-button>
     </n-space>
      </n-tab-pane>








      <n-tab-pane name="signup" tab="注册">
        <n-form>
          <n-form-item-row
            label="用户名"
            :required="true"
            :validation-status="inputUserNameStatus"
            :feedback="inputUserNameFeedbackval"
            >
            <n-input
              ref="registerUserNameRef"
              v-model:value="registerObj.uName"
              placeholder="请输入用户名"
              @keydown.enter="register"
              @blur="checkIsExistsUster"
              maxlength="20"
              show-count
              clearable
            />
          </n-form-item-row>

          <n-form-item-row label="微信">
            <n-input
              ref="registerWechatRef"
              v-model:value="registerObj.uWechat"
              placeholder="请输入微信手机号 / 微信名"
              @keydown.enter="register"
              maxlength="100"
              show-count
              clearable
            />
          </n-form-item-row>

          <n-form-item-row label="邮箱">
            <n-auto-complete
              ref="registerEmailRef"
              v-model:value="registerObj.uEmail"
              placeholder="请输入邮箱 / 任意邮箱"
              @keydown.enter="register"
              :input-props="{ autocomplete: 'disabled' }"
              :options="emailOptions"
              clearable
            />
          </n-form-item-row>

          <n-form-item-row label="电话">
            <n-input
              ref="registerTelephoneRef"
              v-model:value="registerObj.uCellphone"
              placeholder="请输入电话号码"
              @keydown.enter="register"
              @blur="checkTelephone"
              maxlength="11"
              show-count
              clearable
            />
          </n-form-item-row>
          
          <n-form-item-row label="密码" :required="true">
            <n-input
              ref="registerUserPwdRef"
              v-model:value="registerObj.uPwdword"
              :required="true"
              placeholder="请输入密码"
              @keydown.enter="register"
              show-password-on="mousedown"
              type="password"
              clearable
            />
          </n-form-item-row>
          <n-form-item-row label="确认密码" :required="true">
            <n-input
              ref="registerRPwdRef"
              v-model:value="registerObj.uRPwdword"
              :required="true"
              placeholder="请重新输入密码"
              @keydown.enter="register"
              show-password-on="mousedown"
              type="password"
              clearable
            />
          </n-form-item-row>
          <n-form-item-row label="头像URL">
            <n-input
              ref="registerAvatorNetUrlRef"
              v-model:value="registerObj.uNetavator_url"
              placeholder="网络头像链接"
              @keydown.enter="register"
              show-password-on="mousedown"
              clearable
            />
          </n-form-item-row>



          <!-- <n-form-item-row label="头像">
            <n-upload
              ref="registerAvatorUploadRef"
              multiple
              directory-dnd
              :custom-request="handleUpload"
              @remove="handleRemove"
              :max="1"
            >
              <n-upload-dragger>
                <div style="margin-bottom: 10px">
                  <n-icon size="24" :depth="1">
                    <ArchiveIcon />
                  </n-icon>
                </div>
                <n-text depth="3" style="font-size: 12px;">点击或者拖动到此上传头像</n-text>
                <n-p depth="3" style="margin: 0 0; font-size: 12px;">请勿上传敏感信息, 比如银行、信用卡等</n-p>
              </n-upload-dragger>
            </n-upload>
          </n-form-item-row> -->

          <n-form-item-row label="头像" :required="true">
            <n-upload
              ref="registerAvatorUploadRef"
              list-type="image-card"
              :max="1"
              :custom-request="handleUpload"
              @remove="handleRemove"
              :file-list="avatarFiles"
              @change="handleFileChange"
            >
              <n-upload-dragger>
                <div class="upload-tips">
                  <n-icon size="24" depth="3"><ArchiveIcon /></n-icon><br/>
                  <n-text depth="3" style="font-size: 10px;">点击或拖拽</n-text><br/>
                  <n-p depth="3" style="margin: 0 0; font-size: 10px;">勿传敏感信息</n-p>
                </div>
              </n-upload-dragger>
              
              <template #file="{ file }">
                <n-image
                  :src="file.url"
                  :alt="file.name"
                  width="100"
                  height="100"
                  object-fit="cover"
                  preview-disabled
                >
                  <template #placeholder>
                    <n-spin size="small" />
                  </template>
                </n-image>
              </template>
            </n-upload>
          </n-form-item-row>



        </n-form>
        <n-button type="primary" block secondary strong @click="register">
          注册
        </n-button>
      </n-tab-pane>






    </n-tabs>
    </n-spin>

  </n-card>
</template>

<script setup lang="ts">
import {VaeStore} from "../../store";
import {ref, computed, reactive,inject,watch,nextTick,onMounted} from 'vue'
import {storeToRefs} from "pinia";
import {setCookies,storage} from '../../utils/auth'
import {getUserId} from '../../utils/function'
import { useDialog, useMessage,InputInst , useNotification, UploadFileInfo} from 'naive-ui'
import { ArchiveOutline as ArchiveIcon } from '@vicons/ionicons5'
import request from '@/utils/request'
import type { BaseResponse } from "@/types/request";
import { useRouter ,} from 'vue-router'
const router = useRouter()



const notification = useNotification();
const emit = defineEmits(['setShowModal']);
const dialog = useDialog()
const store = VaeStore();
let { clientWidth,userInfo} = storeToRefs(store);
const message=useMessage();
const showloading = ref(false);


// 注册相关 ref
const registerUserNameRef= ref<InputInst | null>(null) // 注册用户名
const registerWechatRef= ref<InputInst | null>(null) // 微信
const registerEmailRef= ref<InputInst | null>(null) // 邮箱
const registerTelephoneRef= ref<InputInst | null>(null) // 电话
const registerUserPwdRef= ref<InputInst | null>(null) // 密码
const registerRPwdRef= ref<InputInst | null>(null) // 确认密码
const registerAvatorNetUrlRef= ref(null) // 头像URL
const registerAvatorUploadRef= ref(null) // 头像上传

// 登录相关 ref
const loginUserNameRef= ref<InputInst | null>(null)
const loginUserPwdRef= ref<InputInst | null>(null)

// tab切换
const activeTab = ref('signin');

interface UserData {
  userName: string;
  password: string;
}

const userdata = reactive({
  across_num: '',
  avatarBase64: '',
  avatar_url: '',
  create_tm: '',
  email: '',
  encrypt_pwd: '',
  encryption_algorithm: '',
  freeze_ornnt: '',
  id: '',
  role_num: '',
  tel_num: '',
  update_tm: '',
  username: '',
  wechat_abt: '',
})

const registerObj = reactive({
  uName:'', // 注册用户名
  uWechat:'', // 注册微信 信息
  uEmail:'', // 注册邮箱
  uCellphone:'', // 注册手机号
  uPwdword:'', // 注册密码
  uRPwdword:'', // 重新输入密码
  uNetavator_url:'', // 网络头像链接
  uUploadavator_url:'', // 自己上传的头像的链接 （minio存入的桶地址）
})

const loginForm = reactive({
  uName:'',
  uPwdword:'',
})  

// 注册邮箱自动填充后缀
const emailOptions= computed(() => {
  return ['@qq.com', '@gmail.com', '@163.com'].map((suffix) => {
    const prefix = registerObj.uEmail.split('@')[0]
    return {
      label: prefix + suffix,
      value: prefix + suffix
    }
  })
});

//用户登录
const loginBtn = async () => {
  let {uName,uPwdword} =loginForm;
  if(!uName){
    message.error('用户名不能为空！');
    loginUserNameRef.value?.focus()
    return;
  }
  if(!uPwdword){
    message.error('密码不能为空！');
    loginUserPwdRef.value?.focus()
    return;
  }

  try {
      showloading.value = true;
      const res = await request.post("/dragon/login",loginForm);
      console.log(res)
      if(res.data && res.code === 200) {
        if (res.data.freeze_ornnt == 1){
          message.error('账号已被冻结，请联系管理员!');
          showloading.value = false;
          return;
        }
        message.success(res.msg);

        store.setuserInfo(res.data); //pinia存储信息
        store.setappleToken('这里是token');

        setCookies('appleToken','这里是token')//cookie存储用户信息
        // setCookies('userInfo',JSON.stringify(res.data))

        // 设置 storage
        storage.set('userInfo', res.data, {
          type: 'local', 
          // expires: 1, // 一天过期
          encrypt: false, // 是否加密
        });
        storage.set('userInfo', res.data, {type: 'session', encrypt: false,});
        storage.set('userInfo', res.data, { type: 'cookie', encrypt: false,});

        // 调用父组件 方法 关闭弹框，刷新页面
        emit('setShowModal');
        // 登录成功跳转首页
        router.push({ path: `/home` });
        location.reload();
        showloading.value = false;
      } else if (res.code == 666) {
        Object.assign(loginForm, {uName: '', uPwdword: ''});
        message.error(res.msg);
        showloading.value = false;
      } else {
        Object.assign(loginForm, {uName: '', uPwdword: ''});
        message.error(res.msg);
        showloading.value = false;
      }
    } catch (err) {
      Object.assign(loginForm, {uName: '', uPwdword: ''});
      showloading.value = false;
      console.error((err as Error).message);
    }
  

  // login_Request(userName,password);
};
//登录接口
const   login_Request=(userName:string,password:string)=>{
  // console.log(userName,password)
  // showloading.value = true;
  // // 这里调用登录接口，登录成功之后保存用户信息，
  // let obj={
  //   "userHead":"https://tse2-mm.cn.bing.net/th/id/OIP-C.yp-D-KHI3e2nN4eMBJcEVAAAAA?rs=1&pid=ImgDetMain",
  //   "userId":"apple1704348343094",
  //   "userName":"1",
  //   "userPassword":"63b6e6722610b3b027779e59e44fddb9"
  // };
  // //pinia存储信息
  // store.setuserInfo(obj);
  // store.setappleToken('这里是token');
  // //cookie存储用户信息
  // setCookies('appleToken','这里是token')
  // setCookies('userInfo',JSON.stringify(obj))
  // // 调用父页面 方法 关闭弹框，刷新页面
  // emit('setShowModal');
  // location.reload();
}
//用户注册
const register= async () => {
  // 解构赋值
  let {uName,uWechat,uEmail,uCellphone,uPwdword,uRPwdword,uNetavator_url,uUploadavator_url} = registerObj;
  if(!uName) {
    message.error('用户名不能为空！');
    registerUserNameRef.value?.focus()
    return;
  }
  if(!uPwdword) {
    message.error('请输入您的密码！');
    registerUserPwdRef.value?.focus();
    return;
  } 
  if(!uRPwdword) {
    message.error('请输入确认密码！');
    registerRPwdRef.value?.focus();

    return;
  }
  if(uPwdword !== uRPwdword) {
    message.error('两次密码输入不一致!');
    registerRPwdRef.value?.focus();
    registerObj.uRPwdword = ''
    return;
  }
  if (isUploadAvatarDone.value) {
    showloading.value=true;
    console.log("用户注册信息", registerObj)
    try {
      const res = await request.post<BaseResponse<UserData>>("/dragon/register",registerObj);
      if (res.code && res.code == 200){
        message.success('注册成功!');
        activeTab.value = 'signin'; // 切换回登录标签
        // 可选：清空注册表单
        Object.assign(registerObj, {uName: '',uWechat: '',uEmail: '',uCellphone: '',uPwdword: '',uRPwdword: '',uNetavator_url: '',uUploadavator_url: '',});
        // 可选：自动填充用户名到登录表单
        loginForm.uName = registerObj.uName; 
      }
      showloading.value = false
    } catch (err) {
      showloading.value = false
      console.error((err as Error).message);
    }
  } else {
    message.warning('请先上传头像!');
  }
  
}

watch(activeTab, (newVal) => {
  if (newVal === 'signin') {
    inputUserNameStatus.value='';
    inputUserNameFeedbackval.value=''
    // 切换到登录的时候删除登录表单头像数据
    isUploadAvatarDone.value = false;
    avatarFiles.value = [];
    registerObj.uUploadavator_url = '';

    nextTick(() => {
      loginUserNameRef.value?.focus()
    })
  }
})

//验证用户名是否重复，不需要可以删除
const inputUserNameFeedbackval=ref<string|undefined>(undefined);
const inputUserNameStatus=ref<string|undefined>(undefined);
const checkIsExistsUster = async () => {

  if(registerObj.uName !== '' && registerObj.uName !== undefined) { 
    try {
      const res = await request.post<BaseResponse<UserData>>("/dragon/checkUser",registerObj);
        console.log(res)
        // @ts-ignore
      if(res.data == 0 && registerObj.uName !== '') {
        message.success(res.msg);
        inputUserNameStatus.value='success';
        inputUserNameFeedbackval.value='用户名可用'
      } else {
        message.warning("用户名不可用！");
        registerObj.uName = '' // 清空输入内容
        inputUserNameStatus.value='';
        inputUserNameFeedbackval.value='用户名不可用!'
      }
    } catch (err) {
      console.error((err as Error).message);
    }

  }

}


// 验证手机号码是否合法
const isValidTelephone = (telephone: string) => {
  const reg = /^1[3-9]\d{9}$/;
  return reg.test(telephone);
}
// 失去焦点时验证手机号码
const inputTelephoneFeedbackval=ref<string|undefined>(undefined);
const inputTelephoneStatus=ref<string|undefined>(undefined);
const checkTelephone = () => {
  const telephone = registerObj.uCellphone;
  if (telephone) {
    if (isValidTelephone(telephone)) {
      inputTelephoneStatus.value = 'success';
      inputTelephoneFeedbackval.value = '手机号码格式正确';
      message.success(inputTelephoneFeedbackval.value)
    } else {
      inputTelephoneStatus.value = 'error';
      inputTelephoneFeedbackval.value = '请输入正确的手机号码';
      message.error(inputTelephoneFeedbackval.value)
      registerObj.uCellphone = ''
    }
  } else {
    inputTelephoneStatus.value = undefined;
    inputTelephoneFeedbackval.value = undefined;
    registerObj.uCellphone = ''
  }
}




// ======================= 上传头像 =======================
const isUploadAvatarDone = ref(false); //头像是否上传成功
const avatarFiles = ref<UploadFileInfo[]>([]);

// 文件状态变化处理
const handleFileChange = (options: { file: UploadFileInfo, fileList: UploadFileInfo[] }) => {
  avatarFiles.value = options.fileList;
};

// 独立生成器函数（网页8优化版）
function generateUniqueName(ext: string, username: string) {
  const timestamp = (Date.now() - new Date('2024-01-01').getTime())
    .toString(36)
    .toUpperCase();
  const randomPart = Math.random().toString(36).slice(2, 6);
  // return `${timestamp}_${randomPart}.${ext}`;
  return `${username}.${ext}`;
}
// 上传处理
const handleUpload = async (options: { file: UploadFileInfo }) => {
  console.log(options)
  try {
    // // 注册名必须填写才能上传头像
    if (!registerObj.uName) {
      message.warning("请先填写用户名!");
      avatarFiles.value = [];
      return;
    }
    // // 文件存在性检查
    if (!options?.file || !(options.file.file instanceof File)) {
      throw new Error('未选择有效文件');
    }

    // // 校验文件后缀
    const initialValues = ['bmp','jpg','png','tif','gif','pcx','tga','exif','fpx','svg','psd',
    'cdr','pcd','dxf','ufo','eps','ai','raw','WMF','webp','avif','apng'];
    const safeAvatarFilename = ref(new Set(initialValues)); 
    const lastDotIndex = options.file.name.lastIndexOf('.');
    const fileSuffix =  (lastDotIndex > 0) ? options.file.name.substring(lastDotIndex + 1) : '';
    if (!safeAvatarFilename.value.has(fileSuffix)) {
      message.error("请上传安全的头像文件!");
      avatarFiles.value = [];
      return;
    }

     // 文件名生成逻辑 --------------------------------------------------------
     const originalFile = options.file.file as File;
    const fileExtension = originalFile.name.split('.').pop() || 'png';
    // 将用户名作为头像文件名（用户名不重复的）
    const sanitizedName = generateUniqueName(fileExtension,registerObj.uName);
    // 创建新文件对象
    const modifiedFile = new File([originalFile], sanitizedName, { type: originalFile.type});
    // 更新上传文件引用
    options.file.file = modifiedFile;
    options.file.name = sanitizedName;
    // ------------------------------------------------------------------------
    const formData = new FormData();
    formData.append('avatar', options.file.file as File);
    formData.append('userId', registerObj.uName);

    // 显示上传进度
    options.file.status = 'uploading';
    options.file.percentage = 10;
    showloading.value = true
    const res = await request.upload<{ url: string }>(
      "/dragon/uploadAvatar",
      options.file.file,
      { userId: registerObj.uName }, // 可添加额外参数
      { headers: { 'X-Upload-Type': 'avatar' } },
      { fieldName: 'avatar' } // 和后端 @RequestParam 名称保持一致
    );
    if (res.code === 200) {
      message.success("头像上传成功!");
      options.file.status = 'finished';
      // @ts-ignore
      options.file.url = res.data; // 显示缩略图
      // @ts-ignore
      registerObj.uUploadavator_url = res.data;
      isUploadAvatarDone.value = true;
      showloading.value = false
    }

  } catch (error) {
    options.file.status = 'error';
    message.error(`上传失败: ${(error as Error).message}`);
  }
};

// 删除处理（完整版）
const handleRemove = async (options: { file: UploadFileInfo }) => {
  try {
    // 调用后端删除接口
    // await request.delete('/dragon/deleteAvatar', {
    //   params: { url: options.file.url }
    // });

    console.log("删除头像")
    // 更新数据
    isUploadAvatarDone.value = false;
    avatarFiles.value = [];
    registerObj.uUploadavator_url = '';
    message.info('头像已删除');
  } catch (error) {
    message.error(`删除失败: ${(error as Error).message}`);
  }
};
// ======================= 上传头像 =======================



onMounted(() => {
  // @ts-ignore
  userdata.across_num = userInfo._object.userInfo.across_num
  // @ts-ignore
  userdata.avatarBase64 = userInfo._object.userInfo.avatarBase64
  // @ts-ignore
  userdata.avatar_url = userInfo._object.userInfo.avatar_url
  // @ts-ignore
  userdata.create_tm = userInfo._object.userInfo.create_tm
  // @ts-ignore
  userdata.email = userInfo._object.userInfo.email
  // @ts-ignore
  userdata.encrypt_pwd = userInfo._object.userInfo.encrypt_pwd
  // @ts-ignore
  userdata.encryption_algorithm = userInfo._object.userInfo.encryption_algorithm
  // @ts-ignore
  userdata.freeze_ornnt = userInfo._object.userInfo.freeze_ornnt
  // @ts-ignore
  userdata.id = userInfo._object.userInfo.id
  // @ts-ignore
  userdata.role_num = userInfo._object.userInfo.role_num
  // @ts-ignore
  userdata.tel_num = userInfo._object.userInfo.tel_num
  // @ts-ignore
  userdata.update_tm = userInfo._object.userInfo.update_tm
  // @ts-ignore
  userdata.username = userInfo._object.userInfo.username
  // @ts-ignore
  userdata.wechat_abt = userInfo._object.userInfo.wechat_abt
})
</script>

<style lang="scss" scoped>
.n-upload-dragger {
  padding: 6px;
}

/* 上传区域样式 */
.upload-tips {
  padding: 12px;
  text-align: center;
}

/* 缩略图容器 */
.n-upload-file-list-image-card {
  gap: 8px;
  margin-top: 8px;
}

/* 图片预览样式 */
.n-image {
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.2s;
  
  &:hover {
    transform: scale(1.05);
  }
}


/* 必填项星号样式 */
// .n-form-item-label__required::before {
//   content: '*';
//   color: #f5222d;
//   margin-right: 4px;
//   font-size: 14px;
//   vertical-align: middle;
// }
</style>
